//
//  NewsViewController.m
//  SnailPost
//
//  Created by 抠泥ser on 16/3/7.
//  Copyright © 2016年 抠泥ser. All rights reserved.
//

#import "NewsViewController.h"
#import <Masonry.h>
#import "BlogCollectionViewCell.h"
#import "CartoonCollectionViewCell.h"
#import "DuangCollectionViewCell.h"
#import "ForumCollectionViewCell.h"
#import "GameCollectionViewCell.h"
#import "InternetCollectionViewCell.h"
#import "LotteryTicketCollectionViewCell.h"
#import "ReadCollectionViewCell.h"
#import "WebDetailsViewController.h"
#import "NewsDetailViewController.h"
#import "DetailsViewController.h"
#import "SearchViewController.h"
#import "AFNetworkReachabilityManager.h"

@interface NewsViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewAccessibilityDelegate, BlogDelegate, CartoonDelegate, DuangDelegate, ForumDelegate, GameDelegate, InternetDelegate, LotteryTicketDelegate, ReadDelegate>

@property (nonatomic, strong)UIScrollView *scrollView;

@property (nonatomic, strong)UICollectionView *collectionView;

@property (nonatomic, strong)NSMutableArray *buttonArr;/**< 按钮数组*/

@end

@implementation NewsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 创建collectionView
    [self createCollectionView];
    // 创建scrollView
    [self createScrollView];
    
    self.navigationItem.title = @"新闻";
   
    
    [self rightnavigationItem];
    
    [self internetJudgement];
}

- (void)rightnavigationItem
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Search@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(searchAction:)];

 
}

- (void)searchAction:(UIBarButtonItem *)search
{
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:searchVC];
    
    [self presentViewController:navi animated:YES completion:^{
        
    }];
}

#pragma mark - 创建collectionView
- (void)createCollectionView
{
    // CollectionViewFlowLayout创建
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height);
    
    // 横屏开启
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 预留边界
    layout.sectionInset = UIEdgeInsetsMake(20, 0, 0, 0);
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 列间距
    layout.minimumLineSpacing = 0;
    // collectionView创建
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor clearColor];
    // 取消边缘弹动
    _collectionView.bounces = NO;
    // 签订代理
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    // 允许滚动
    _collectionView.pagingEnabled = YES;
    // 注册重用池
    [_collectionView registerClass:[ReadCollectionViewCell class] forCellWithReuseIdentifier:@"readCell"];
    [_collectionView registerClass:[InternetCollectionViewCell class] forCellWithReuseIdentifier:@"internetCell"];
    [_collectionView registerClass:[DuangCollectionViewCell class] forCellWithReuseIdentifier:@"duangCell"];
    [_collectionView registerClass:[GameCollectionViewCell class] forCellWithReuseIdentifier:@"gameCell"];
    [_collectionView registerClass:[CartoonCollectionViewCell class] forCellWithReuseIdentifier:@"cartoonCell"];
    [_collectionView registerClass:[LotteryTicketCollectionViewCell class] forCellWithReuseIdentifier:@"lotteryTicketCell"];
    [_collectionView registerClass:[BlogCollectionViewCell class] forCellWithReuseIdentifier:@"blogCell"];
    [_collectionView registerClass:[ForumCollectionViewCell class] forCellWithReuseIdentifier:@"forumCell"];
    [self.view addSubview:_collectionView];
    
}

#pragma mark - collectionView必须实现的两个方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    // collectionView行数设置
    return 8;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        InternetCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"internetCell" forIndexPath:indexPath];
        cell.delegate = self;
        return cell;
    } else if (indexPath.row == 1) {
        ReadCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"readCell" forIndexPath:indexPath];
        cell.delegate = self;
        return cell;
    } else if (indexPath.row == 2) {
        DuangCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"duangCell" forIndexPath:indexPath];
         cell.delegate = self;
        return cell;
    } else if (indexPath.row == 3) {
        GameCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"gameCell" forIndexPath:indexPath];
         cell.delegate = self;
        return cell;
    } else if (indexPath.row == 4) {
        CartoonCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cartoonCell" forIndexPath:indexPath];
         cell.delegate = self;
        return cell;
    }else if (indexPath.row == 5) {
        LotteryTicketCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"lotteryTicketCell" forIndexPath:indexPath];
         cell.delegate = self;
        return cell;
    } else if (indexPath.row == 6) {
        BlogCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"blogCell" forIndexPath:indexPath];
         cell.delegate = self;
        return cell;
    } else {
        ForumCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"forumCell" forIndexPath:indexPath];
         cell.delegate = self;

        return cell;
    }
    
}

#pragma mark - 创建滑动条ScrollView
- (void)createScrollView
{
    // Masonry适配
    UIView *superView = [UIView new];
    // superView.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:superView];
    [superView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(64);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(self.view.bounds.size.width, 40));
    }];
    self.scrollView = [UIScrollView new];
    [_scrollView NightWithType:UIViewColorType2];
    [superView addSubview:_scrollView];
    _scrollView.showsHorizontalScrollIndicator = NO;
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(superView);
    }];
    UIView *container = [UIView new];
    [_scrollView addSubview:container];
    [container mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_scrollView);
        make.top.equalTo(self.view).with.offset(64);
        make.height.equalTo(_scrollView);
    }];
    
    int count = 8;
    
    UIView *lastView = nil;
    // 添加分栏名称
    NSArray *arr = @[@"互联网", @"读书", @"duang", @"游戏", @"漫画", @"彩票", @"博客", @"论坛"];
    // 初始化 用于添加按钮
    self.buttonArr = [NSMutableArray array];
    for (int i = 0; i < count; ++i) {
        UIView *selectView = [UIView new];
        [container addSubview:selectView];
        // 滚动条添加按钮
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        [selectView addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(selectView);
            button.tag = 100 + i;
            [button setTitle:arr[i] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.buttonArr addObject:button];
        }];
        
        [selectView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.and.bottom.equalTo(container);
            make.width.mas_equalTo(@((WIDTH - 20) / 5));
            if (lastView) {
                make.left.mas_equalTo(lastView.mas_right);
            } else {
                make.left.mas_equalTo(container.mas_left);
            }
        }];
        lastView = selectView;
    }
    [container mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(lastView.mas_right);
    }];
    // 首次进入页面 第一个按钮为红色
    [_buttonArr[0] setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
}

#pragma mark - button点击事件
- (void)buttonAction:(UIButton *)button
{
    // 遍历button 所有button为黑色
    for (UIButton *button in _buttonArr) {
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    // 选中按钮为红色
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    // collectionView跟随按钮动
    [_collectionView setContentOffset:CGPointMake(self.view.bounds.size.width * (button.tag - 100), 0) animated:YES];
}

//scollview与collectionview相互关联

#pragma mark - scrollView协议方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == _collectionView) {
        _scrollView.contentOffset = CGPointMake(_collectionView.contentOffset.x / WIDTH * (WIDTH - 20) / 5, 0);
    }
    // 根据偏移量算出在哪个分栏
    NSInteger i = scrollView.contentOffset.x / self.view.bounds.size.width;
    for (UIButton *button in _buttonArr) {
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    // 界面对应的分栏为红色
    [_buttonArr[i] setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
}

//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
//{
//    if (scrollView == _collectionView)
//    {
//        NSInteger i = _scrollView.contentOffset.x / (WIDTH - 20) / 5;
//        for (UIButton *button in _buttonArr) {
//            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        }
//        [_buttonArr[i] setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
//    }
//}

- (void)internetJudgement
{
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
                
            case AFNetworkReachabilityStatusUnknown: // 未知网络
            {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前为未知网络" preferredStyle:UIAlertControllerStyleAlert];
                /* 创建action对象 */
                UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    
                }];
                
                /* alert添加action对象 */
                [alert addAction:actionConfirm];
                
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
                
                break;
                
            }
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
            {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲!无网络!请查看网络设置" preferredStyle:UIAlertControllerStyleAlert];
                /* 创建action对象 */
                UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    
                }];
                
                /* alert添加action对象 */
                [alert addAction:actionConfirm];
                
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
                
                break;
                
            }
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
            {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲!正在使用手机3G/4G网" preferredStyle:UIAlertControllerStyleAlert];
                /* 创建action对象 */
                UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    
                }];
                
                /* alert添加action对象 */
                [alert addAction:actionConfirm];
                
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
                
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
            {
                NSLog(@"WIFI");
                UIAlertView *alertView2 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"亲!正在使用wifi" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alertView2 show];
                break;
            }
        }
    }];
    
    // 3.开始监控
    [manager startMonitoring];
}

- (void)BlogValue:(NSString *)url :(NSString *)title
{
    self.hidesBottomBarWhenPushed = YES;
    WebDetailsViewController *WDVC = [[WebDetailsViewController alloc] init];
    WDVC.str = url;
    WDVC.title = title;
    [self.navigationController pushViewController:WDVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

- (void)CartoonValue:(NSString *)url :(NSString *)title
{
    self.hidesBottomBarWhenPushed = YES;
    DetailsViewController *DVC = [[DetailsViewController alloc] init];
    DVC.str = url;
    DVC.title = title;
    [self.navigationController pushViewController:DVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}
- (void)DuangValue:(NSString *)url :(NSString *)title
{
    self.hidesBottomBarWhenPushed = YES;
    WebDetailsViewController *WDVC = [[WebDetailsViewController alloc] init];
    WDVC.str = url;
    WDVC.title = title;
    [self.navigationController pushViewController:WDVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}
- (void)ForumValue:(NSString *)url :(NSString *)title
{
    self.hidesBottomBarWhenPushed = YES;
    WebDetailsViewController *WDVC = [[WebDetailsViewController alloc] init];
    WDVC.str = url;
    WDVC.title = title;
    [self.navigationController pushViewController:WDVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}
- (void)GameValue:(NSString *)url :(NSString *)title
{
    self.hidesBottomBarWhenPushed = YES;
    WebDetailsViewController *WDVC = [[WebDetailsViewController alloc] init];
    WDVC.str = url;
    WDVC.title = title;
    [self.navigationController pushViewController:WDVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}
- (void)InternetValue:(NSString *)url :(NSString *)title
{
    self.hidesBottomBarWhenPushed = YES;
    NewsDetailViewController *NDVC = [[NewsDetailViewController alloc] init];
    NDVC.str = url;
    NDVC.title = title;
    [self.navigationController pushViewController:NDVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

- (void)LotteryTicketValue:(NSString *)url :(NSString *)title
{
    self.hidesBottomBarWhenPushed = YES;
    WebDetailsViewController *WDVC = [[WebDetailsViewController alloc] init];
    WDVC.str = url;
    WDVC.title = title;
    [self.navigationController pushViewController:WDVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

- (void)ReadValue:(NSString *)url :(NSString *)title
{
    self.hidesBottomBarWhenPushed = YES;
    DetailsViewController *DVC = [[DetailsViewController alloc] init];
    DVC.str = url;
    DVC.title = title;
    [self.navigationController pushViewController:DVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
